package fr.sedoo.metadata.client.ui.widget.field.primitive;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;

import fr.sedoo.commons.client.util.ElementUtil;
import fr.sedoo.metadata.client.ui.widget.field.api.IsDisplay;
import fr.sedoo.metadata.client.ui.widget.field.api.IsEditor;
import fr.sedoo.metadata.client.ui.widget.field.constant.FieldConstant;
import fr.sedoo.metadata.client.ui.widget.field.impl.KeyComparator;

public abstract class ListBoxField extends HorizontalPanel implements IsDisplay, IsEditor {

	protected static final int UNSELECTED_ID_INDEX = 0;

	protected Label label;
	protected ListBox listBox;

	public ListBoxField() {
		super();
		setWidth(FieldConstant.HUNDRED_PERCENT);
		label = new Label();
		listBox = new ListBox();
		ElementUtil.hide(label);
		ElementUtil.hide(listBox);
		add(listBox);
		add(label);
	}

	protected void selectByValue(String value) {
		if ((value != null) && (value.trim().length() > 0)) {
			for (int index = 0; index < listBox.getItemCount(); index++) {
				if (KeyComparator.compareLosely(listBox.getValue(index).toLowerCase(), value.toLowerCase())) {
					listBox.setSelectedIndex(index);
					break;
				}
			}
		}

	}

	@Override
	public void reset() {
		listBox.setSelectedIndex(UNSELECTED_ID_INDEX);
		label.setText("");
	}

}
